<template>
  <div class="product-management">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入产品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="可领取" :value="1" />
            <el-option label="已下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级">
          <el-select v-model="searchForm.difficulty" placeholder="请选择难度" clearable style="width: 120px">
            <el-option label="简单" :value="1" />
            <el-option label="普通" :value="2" />
            <el-option label="中等" :value="3" />
            <el-option label="困难" :value="4" />
            <el-option label="专家" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增产品</el-button>
          <el-button type="warning" :icon="Download" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6" v-for="stat in productStats" :key="stat.title">
        <el-card class="stat-card" :class="stat.type">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="24"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="产品信息" min-width="300">
          <template #default="{ row }">
            <div class="product-info">
              <el-image
                :src="row.images[0]"
                :preview-src-list="row.images"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 4px; margin-right: 12px"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-details">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-category">{{ row.category }}</div>
                <div class="product-desc">{{ row.description }}</div>
                <div class="product-tools">
                  <el-tag
                    v-for="tool in row.tools"
                    :key="tool"
                    size="small"
                    type="info"
                    style="margin-right: 4px"
                  >
                    {{ tool }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价(元)" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.unitPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productionTime" label="制作时间" width="100">
          <template #default="{ row }">
            {{ formatTime(row.productionTime) }}
          </template>
        </el-table-column>
        <el-table-column label="难度等级" width="120">
          <template #default="{ row }">
            <el-rate
              v-model="row.difficulty"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}级"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="getStockTagType(row.stock)">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="领取/完成" width="120">
          <template #default="{ row }">
            <div class="task-stats">
              <div>领取: {{ row.claimedCount }}</div>
              <div>完成: {{ row.completedCount }}</div>
              <div>通过: {{ row.approvedCount }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '可领取' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleAction(command, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toggleStatus">
                    {{ row.status === 1 ? '下架产品' : '上架产品' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除产品</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 产品详情对话框 -->
    <ProductDetail
      v-model:visible="detailVisible"
      :product-id="currentProductId"
    />

    <!-- 新增/编辑产品对话框 -->
    <ProductForm
      v-model:visible="formVisible"
      :mode="formMode"
      :data="currentProduct"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Picture, ArrowDown } from '@element-plus/icons-vue'
import { productAPI } from '@/api/product'
import ProductDetail from './components/ProductDetail.vue'
import ProductForm from './components/ProductForm.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const categories = ref([])

const searchForm = reactive({
  name: '',
  category: '',
  status: null,
  difficulty: null
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 产品统计数据
const productStats = ref([
  { title: '总产品数', value: '0', icon: 'Box', type: 'primary' },
  { title: '可领取', value: '0', icon: 'Check', type: 'success' },
  { title: '库存不足', value: '0', icon: 'Warning', type: 'warning' },
  { title: '总完成数', value: '0', icon: 'Star', type: 'danger' }
])

// 对话框状态
const detailVisible = ref(false)
const formVisible = ref(false)
const formMode = ref('create')
const currentProductId = ref(null)
const currentProduct = ref(null)

// 格式化时间
const formatTime = (minutes) => {
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
}

// 获取产品列表
const fetchProductList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      name: searchForm.name || undefined,
      category: searchForm.category || undefined,
      status: searchForm.status !== null ? searchForm.status : undefined,
      difficulty: searchForm.difficulty !== null ? searchForm.difficulty : undefined
    }

    const response = await productAPI.getList(params)
    tableData.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取产品分类
const fetchCategories = async () => {
  try {
    const response = await productAPI.getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取产品分类失败:', error)
  }
}

// 获取产品统计
const fetchProductStats = async () => {
  try {
    const response = await productAPI.getStats()
    const stats = response.data || {}
    productStats.value[0].value = stats.totalProducts || '0'
    productStats.value[1].value = stats.onlineProducts || '0'
    productStats.value[2].value = stats.lowStockProducts || '0'
    productStats.value[3].value = stats.totalCompleted || '0'
  } catch (error) {
    console.error('获取产品统计失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchProductList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    status: null,
    difficulty: null
  })
  pagination.current = 1
  fetchProductList()
}

// 新增产品
const handleAdd = () => {
  formMode.value = 'create'
  currentProduct.value = null
  formVisible.value = true
}

// 查看详情
const handleViewDetail = (row) => {
  currentProductId.value = row.id
  detailVisible.value = true
}

// 编辑产品
const handleEdit = (row) => {
  formMode.value = 'edit'
  currentProduct.value = { ...row }
  formVisible.value = true
}

// 处理操作
const handleAction = async (command, row) => {
  switch (command) {
    case 'toggleStatus':
      await handleToggleStatus(row)
      break
    case 'delete':
      await handleDelete(row)
      break
  }
}

// 切换产品状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '上架' : '下架'

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}产品「${row.name}」吗？`,
      `${statusText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await productAPI[newStatus === 1 ? 'online' : 'offline'](row.id)
    ElMessage.success(`${statusText}成功`)
    fetchProductList()
    fetchProductStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}产品失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 删除产品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品「${row.name}」吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await productAPI.delete(row.id)
    ElMessage.success('删除成功')
    fetchProductList()
    fetchProductStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除产品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchProductList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchProductList()
}

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  fetchProductList()
  fetchProductStats()
}

// 从详情页编辑
const handleEditFromDetail = (product) => {
  formMode.value = 'edit'
  currentProduct.value = { ...product }
  detailVisible.value = false
  formVisible.value = true
}

// 获取库存标签类型
const getStockTagType = (stock) => {
  if (stock === 0) return 'danger'
  if (stock < 50) return 'warning'
  return 'success'
}

// 初始化
onMounted(() => {
  fetchProductList()
  fetchCategories()
  fetchProductStats()
})
</script>

<style lang="scss" scoped>
.product-management {
  .search-card {
    margin-bottom: 20px;
  }

  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    position: relative;
    overflow: hidden;

    &.primary {
      border-left: 4px solid #409eff;
    }

    &.success {
      border-left: 4px solid #67c23a;
    }

    &.warning {
      border-left: 4px solid #e6a23c;
    }

    &.danger {
      border-left: 4px solid #f56c6c;
    }

    .stat-content {
      display: flex;
      align-items: center;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          color: #fff;
        }
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: #2c3e50;
          line-height: 1;
          margin-bottom: 4px;
        }

        .stat-title {
          font-size: 14px;
          color: #909399;
        }
      }
    }

    &.primary .stat-icon {
      background: linear-gradient(135deg, #409eff, #66b1ff);
    }

    &.success .stat-icon {
      background: linear-gradient(135deg, #67c23a, #85ce61);
    }

    &.warning .stat-icon {
      background: linear-gradient(135deg, #e6a23c, #ebb563);
    }

    &.danger .stat-icon {
      background: linear-gradient(135deg, #f56c6c, #f78989);
    }
  }

  .table-card {
    .product-info {
      display: flex;
      align-items: flex-start;

      .product-details {
        flex: 1;

        .product-name {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
          margin-bottom: 4px;
        }

        .product-category {
          font-size: 12px;
          color: #409eff;
          margin-bottom: 4px;
        }

        .product-desc {
          font-size: 12px;
          color: #666;
          margin-bottom: 8px;
          line-height: 1.4;
          max-width: 200px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .product-tools {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }
      }
    }

    .price {
      font-size: 16px;
      font-weight: 600;
      color: #f56c6c;
    }

    .task-stats {
      font-size: 12px;
      color: #666;
      line-height: 1.4;

      div {
        margin-bottom: 2px;
      }
    }

    .image-error {
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #c0c4cc;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>